package com.csw.flink.sql

import org.apache.flink.table.api._
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.api.EnvironmentSettings
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment
import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.types.Row

object Demo02SqlWordCount {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val bsSetting: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner()
      .inStreamingMode()
      .build()

    /**
      * 构建table环境
      */
    val bstableEnv: StreamTableEnvironment = StreamTableEnvironment.create(env,bsSetting)


    /**
      * 创建source表
      */

    /**
      * executeSql：可以执行ddl  dml dql  返回一个tableResult
      * sqlQuery：只可以执行dql  返回一个table对象
      */

    /**
      * 读取json格式的数据，建表语句这种的列名必须和json中的列名一致
      */

    bstableEnv.executeSql(
      """
        |
        |CREATE TABLE student (
        |  id STRING,
        |  name STRING,
        |  age DOUBLE,
        |  gender STRING,
        |  clazz STRING
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'student_json',
        | 'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        | 'properties.group.id' = 'csw',
        | 'format' = 'json',
        | 'json.ignore-parse-errors' = 'true',
        | 'scan.startup.mode' = 'earliest-offset'
        |)
        |
      """.stripMargin)



    /*bstableEnv.from("student").toAppendStream[Row].print()

     env.execute()*/


    /**
      * 创建mysql表
      */

    bstableEnv.executeSql(
      """
        |
        |CREATE TABLE clazz_avg_age (
        |  clazz STRING,
        |  avg_age DOUBLE,
        |  PRIMARY KEY (clazz) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/csw?useUnicode=true&characterEncoding=utf-8&useSSL=false',
        |   'table-name' = 'clazz_avg_age',
        |   'username' = 'root',
        |   'password'= '123456'
        |)
        |
      """.stripMargin)
    /**
      * 实时统计每个班级的平均年龄
      */

    bstableEnv.executeSql(
      """
        |insert into clazz_avg_age
        |select clazz,avg(age) as avg_age from student group by clazz
        |
      """.stripMargin)

  }
}
